import hashlib
import base64
import json
import time
import re
import random
import datetime
from flask import request


def make_sha1(string, encode='utf-8'):
    _hash = hashlib.sha1()
    _hash.update(string.encode(encode))
    _result = _hash.hexdigest()
    return _result


def make_md5(string, encode='utf-8'):
    _hash = hashlib.md5()
    _hash.update(string.encode(encode))
    _result = _hash.hexdigest()
    return _result


def make_base64_encode(string, encode='utf-8'):
    _bytes = base64.b64encode(string.encode(encode))
    _str = str(_bytes, encode)
    return _str


def make_base64_decode(string, encode='utf-8'):
    _bytes = base64.b64decode(string.encode(encode))
    _str = str(_bytes, encode)
    return _str


def make_sha256(string, encode='utf-8'):
    _hash = hashlib.sha256()
    _hash.update(string.encode(encode))
    _result = _hash.hexdigest()
    return _result


def construct_token(data):
    _data = json.dumps(data)
    _token = make_base64_encode(_data)
    return _token


def filter_key(dic, keys):
    _dic = dict()
    for cur in dic:
        if cur in keys:
            _dic[cur] = dic[cur]
    return _dic


def create_id():
    m = hashlib.md5(str(time.clock()).encode('utf-8'))
    return m.hexdigest()


def parse_token(token):
    _token = make_base64_decode(token)
    _token = json.loads(_token)
    return _token


def get_token():
    token = request.headers.get('Token')
    token = parse_token(token)
    return token


def get_ranges():
    _range = request.headers.get('Range')
    print(_range)
    if not _range:
        return
    else:
        v = re.match(r'bytes=(\d+)-((\d+)?)', _range)
        return {
            "start": v.group(1),
            "end": v.group(2)
        }


def get_ranstr(num):
    H = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    salt = ''
    for i in range(num):
        salt += random.choice(H)
    return salt


def get_now_time():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
